package com.kylin.core.user.event.repository;

import com.kylin.dal.entity.user.*;
import com.kylin.domain.user.command.CreateWechatUserCommand;
import com.kylin.domain.user.command.FindUserByOpenIdCommand;
import com.kylin.domain.user.command.UpdateUserPhoneCommand;
import com.kylin.domain.user.command.UpdateWechatUserCommand;
import com.kylin.shared.common.consts.Constants;
import com.kylin.shared.enums.GenderEnum;
import com.kylin.shared.enums.SwitchState;
import com.kylin.shared.enums.YesNoEnum;
import com.kylin.shared.id.SnowflakeFactory;
import com.kylin.shared.id.impl.SnowflakeIdFactory;
import com.kylin.shared.utils.MappingTools;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;

/**
 * 用户数据处理类
 * @author Damon S.
 * @version v1.0.1
 * @date 2019年11月22日 14:55
 */
@Slf4j
@Component
public class UserDataHandler {

    private final JPAQueryFactory userQueryFactory;
    private final QUserWechatEntry qUserWechatEntry;
    private final QUserMainEntry qUserMainEntry;

    private final UserWechatRepository userWechatRepository;
    private final UserMainRepository userMainRepository;

    private final SnowflakeFactory idFactory = SnowflakeIdFactory.instance();


    public UserDataHandler(@Qualifier("kylinArtworkEntityManager")EntityManager entityManager,
                           UserMainRepository userMainRepository,
                           UserWechatRepository userWechatRepository) {
        this.userQueryFactory = new JPAQueryFactory(entityManager);
        this.qUserMainEntry = QUserMainEntry.userMainEntry;
        this.qUserWechatEntry = QUserWechatEntry.userWechatEntry;

        this.userMainRepository = userMainRepository;
        this.userWechatRepository = userWechatRepository;
    }

    /** 根据openId创建用户 */
    public UserWechatEntry createNew(CreateWechatUserCommand command) {
        // 主表插入一条记录
        UserMainEntry mainEntry = UserMainEntry.builder()
                .id(idFactory.nextId(UserMainEntry.class))
                .state(SwitchState.ON.getCode())
                .removed(YesNoEnum.N.getCode())
                .createdAt(MappingTools.toEpochSecond(command.getCreatedAt()))
                .createdBy(command.getCreatedBy())
                .build();
        this.userMainRepository.saveAndFlush(mainEntry);
        // 微信表插入一条记录
        UserWechatEntry wechatEntry = UserWechatEntry.builder()
                .id(idFactory.nextId(UserWechatEntry.class))
                .userId(mainEntry.getId())
                .openId(command.getOpenId())
                .gender(GenderEnum.NA.getValue())
                .removed(YesNoEnum.N.getCode())
                .createdAt(MappingTools.toEpochSecond(command.getCreatedAt()))
                .createdBy(command.getCreatedBy())
                .updatedAt(Constants.LONG_ZERO)
                .updatedBy(Constants.LONG_ZERO)
                .build();
        return userWechatRepository.saveAndFlush(wechatEntry);
    }

    public Integer updateUserInfo(UpdateWechatUserCommand command) {
        UserWechatEntry wechatEntry = UserWechatEntry.builder()
                .userId(command.getUserId())
                .gender(command.getGender().getValue())
                .nickName(command.getNickName())
                .province(command.getProvince())
                .city(command.getCity())
                .language(command.getLanguage())
                .country(command.getCountry())
                .avatarUrl(command.getAvatarUrl())
                .updatedAt(MappingTools.toEpochSecond(command.getUpdatedAt()))
                .updatedBy(command.getUpdatedBy())
                .build();
        return userWechatRepository.updateWechatUserInfo(wechatEntry);
    }

    public Integer updateUserPhone(UpdateUserPhoneCommand command) {
        UserWechatEntry wechatEntry = UserWechatEntry.builder()
                .userId(command.getUserId())
                .phoneNumber(command.getPhoneNumber())
                .updatedAt(MappingTools.toEpochSecond(command.getUpdatedAt()))
                .updatedBy(command.getUpdatedBy())
                .build();
        return userWechatRepository.updatePhone(wechatEntry);
    }

    public UserWechatEntry findUserByOpenId(FindUserByOpenIdCommand command) {
        return this.userQueryFactory.selectFrom(qUserWechatEntry)
                .where(qUserWechatEntry.openId.eq(command.getOpenId()))
                .fetchOne();
    }


//    private List<UserRelationLogEntry> handle(QueryUserHistoryCommand command) {
//        return hwUserQueryFactory.selectFrom(qUserRelationLogEntry)
////                .where(qUserRelationLogEntry.userId.eq(command.getUserId()))
////                .orderBy(qUserRelationLogEntry.createdAt.asc())
//                .fetch();
//    }
//
//    private List<UserLevelLogEntry> handleLevel(QueryUserHistoryCommand command) {
//        return hwUserQueryFactory.selectFrom(qUserLevelLogEntry)
////                .where(qUserLevelLogEntry.userId.eq(command.getUserId()))
////                .orderBy(qUserLevelLogEntry.createdAt.asc())
//                .fetch();
//    }
//
//    private List<UserRelationLogEntry> handleRelation(QueryUserHistoryCommand command) {
//        return hwUserQueryFactory.selectFrom(qUserRelationLogEntry)
////                .where(qUserRelationLogEntry.userId.eq(command.getUserId()))
////                .orderBy(qUserRelationLogEntry.createdAt.asc())
//                .fetch();
//    }

//    public List<UserWechatEntry> findUserUpgradeByParentId(Long parentId) {
//        return hwUserQueryFactory.selectFrom(qUserUpgradeEntry)
//                .where(qUserUpgradeEntry.upLineId.eq(parentId).and(qUserUpgradeEntry.removed.eq(USER_NOT_REMOVED)))
//                .fetch();
//    }
//
//    public UserWechatEntry findUserUpgrade(Long cpId) {
//        return hwUserQueryFactory.selectFrom(qUserUpgradeEntry)
//                .where(qUserUpgradeEntry.userId.eq(cpId).and(qUserUpgradeEntry.removed.eq(USER_NOT_REMOVED)))
//                .fetchOne();
//    }
//
//    public List<UserWechatEntry> findUserUpgrade(Collection<Long> cpIds) {
//        return hwUserQueryFactory.selectFrom(qUserUpgradeEntry)
//                .where(qUserUpgradeEntry.userId.in(cpIds).and(qUserUpgradeEntry.removed.eq(USER_NOT_REMOVED)))
//                .fetch();
//    }
//
//    public List<UserWechatEntry> findVipsByParentId(Long parentId) {
//        return hwUserQueryFactory.selectFrom(qUserUpgradeEntry)
//                .where(qUserUpgradeEntry.upLineId.eq(parentId)
//                        .and(qUserUpgradeEntry.type.eq("SP").or(qUserUpgradeEntry.type.eq("DS").and(qUserUpgradeEntry.subtype.in("VIP", "VIP1", "VIP2", "VIP3", "VIP4", "VIP5"))))
//                        .and(qUserUpgradeEntry.removed.eq(USER_NOT_REMOVED)))
//                .fetch();
//    }
//
//    public List<UserWechatEntry> findVipsByParentIds(Collection<Long> parentIds){
//        return hwUserQueryFactory.selectFrom(qUserUpgradeEntry)
//                .where(qUserUpgradeEntry.upLineId.in(parentIds)
//                        .and(qUserUpgradeEntry.type.eq("SP").or(qUserUpgradeEntry.type.eq("DS").and(qUserUpgradeEntry.subtype.in("VIP", "VIP1", "VIP2", "VIP3", "VIP4", "VIP5"))))
//                        .and(qUserUpgradeEntry.removed.eq(USER_NOT_REMOVED)))
//                .fetch();
//    }
}
